package loginServlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Hashtable;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import swim2.sessionbeans.*;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
    
    public LoginServlet() {
        super();
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		
		
		try{
			Context ctx = getInitialContext();
			LoginSystemRemote loginSystemRemote = (LoginSystemRemote) ctx.lookup("swim2JNDI");
			String mail = request.getParameter("mail");
			String password = request.getParameter("password");			
			int id = loginSystemRemote.getAuthentication(mail, password);
			if(id == -1) {
				request.setAttribute("login", 0);
				RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
				dispatcher.forward(request, response);
			}
			else {
				boolean isadmin = loginSystemRemote.isAdmin(id);
				if(!isadmin){
					request.setAttribute("id", id);
					RequestDispatcher dispatcher = request.getRequestDispatcher("UserPanel.jsp");
					dispatcher.forward(request, response);
				}
				else {
					request.setAttribute("id", id);
					request.setAttribute("mail", mail);
					request.setAttribute("password", password);
					RequestDispatcher dispatcher = request.getRequestDispatcher("AdminPanel.jsp");
					dispatcher.forward(request, response);
				}
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			PrintWriter out = response.getWriter();
			out.print("Login errato!");
		}
		
		
		

	}

	static public Context getInitialContext() throws Exception{
		
		Hashtable<String,String> env = new Hashtable<String,String>();
		
		env.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		env.put(Context.PROVIDER_URL, "localhost:1099");
	
		return new InitialContext(env);
		
	}
	
}
